package cn.francis.zp.common;

import cn.francis.common.constant.AIConstants;
import cn.francis.common.enums.CommonErrorCode;
import cn.francis.common.exception.BusinessException;
import com.zhipu.oapi.ClientV4;
import com.zhipu.oapi.Constants;
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest;
import com.zhipu.oapi.service.v4.model.ChatMessage;
import com.zhipu.oapi.service.v4.model.ChatMessageRole;
import com.zhipu.oapi.service.v4.model.ModelApiResponse;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张俊辉
 */

@Slf4j
public class ZhiPuChatClientUtil {

    private static final ClientV4 client = new ClientV4.Builder(AIConstants.ZHI_PU_API_KEY).build();

    public static String callChatModel(String prompt) {
        List<ChatMessage> messages = new ArrayList<>();
        messages.add(new ChatMessage(ChatMessageRole.USER.value(), prompt));
        String requestId = String.format("YourRequestId-%d", System.currentTimeMillis());
        ChatCompletionRequest request = ChatCompletionRequest.builder()
                .model(Constants.ModelChatGLM4Flash)
                .stream(Boolean.FALSE)
                .invokeMethod(Constants.invokeMethod)
                .messages(messages)
                .requestId(requestId)
                .build();

        ModelApiResponse response = null;
        try {
            response = client.invokeModelApi(request);
        } catch (Exception e) {
            log.error("质谱异常，原因：{}", response);
            throw new BusinessException("调用异常");
        }
        return response.getData() != null ? response.getData().toString() : "无数据返回";
    }
}
